<?php

namespace app\admin\controller\share;

use app\admin\model\Change;
use app\admin\model\share\CommonShare;
use app\admin\model\share\ShareUser;
use think\Db;
use app\common\controller\Backend;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\common\model\User as FUser;
use think\Validate;
use app\common\library\Auth;
use app\common\model\UserChangeLog;
use app\common\model\ShareUserRoleLog;
use app\common\model\ShareConfig;
use fast\Arr;

/**
 * 分销用户
 *
 * @icon fa fa-circle-o
 */
class User extends Backend
{

    /**
     * User模型对象
     * @var \app\admin\model\share\ShareUser
     */
    protected $relationSearch = true;
    protected $model = null;

    protected $noNeedRight = ['*'];
    protected $all_tuiguang = 0;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\share\ShareUser;
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function indexbar()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $filter = json_decode($this->request->get('filter'), true);
            $param1 = json_decode($this->request->param('filter'), 1);

            $where_agent = '';
            $where = [];
            if (isset($filter['addtime'])) {
                $array = explode('-', $filter['addtime']);
                $begin = strtotime($array[0] . '-' . $array[1] . '-' . $array[2]);
                $end = strtotime($array[3] . '-' . $array[4] . '-' . $array[5]);
                if (!empty($where_agent)) {
                    $where_agent = $where_agent . " and share_user.addtime between " . $begin . ' and ' . "$end";
                } else {
                    $where_agent = "share_user.addtime between " . $begin . ' and ' . "$end";
                }
                unset($param1['addtime']);
            }
            //var_dump($param1);die;
            if (isset($param1['user_flags'])) {
                $where['f.user_flags'] = $param1['user_flags'];
                $param1['f.user_flags'] = $param1['user_flags'];
                unset($param1['user_flags']);
            }
            if (isset($param1['user_id'])) {
                $where['user.id'] = $param1['user_id'];
                $param1['user.id'] = $param1['user_id'];
                unset($param1['user_id']);
            }

            if (isset($param1['mobile'])) {
                $where['user.mobile'] = $param1['user_id'];
                $param1['user.mobile'] = $param1['user_id'];
                unset($param1['user_id']);
            }

            if (isset($filter['role_url'])) {
                if (!empty($where_agent)) {
                    $where_agent = $where_agent . " and role_url like '%" . $filter['role_url'] . "%'";
                } else {
                    $where_agent = "role_url like '%" . $filter['role_url'] . "%'";
                }
                unset($param1['role_url']);
            }

            if (isset($filter['user.staff'])) {
                if (!empty($where_agent)) {
                    $where_agent = $where_agent . " and user.staff =2";
                } else {
                    $where_agent = "user.staff =2";
                }
                unset($param1['role_url']);
            }
            if (isset($filter['user.mobile'])) {
                if (!empty($where_agent)) {
                    $where_agent = $where_agent . " and user.mobile like '%" . $filter['user.mobile'] . "%'";
                } else {
                    $where_agent = "user.mobile like '%" . $filter['user.mobile'] . "%'";
                }
                unset($param1['user.mobile']);
            }
            if (isset($filter['user.username'])) {
                if (!empty($where_agent)) {
                    $where_agent = $where_agent . " and user.username like '%" . $filter['user.username'] . "%'";
                } else {
                    $where_agent = "user.username like '%" . $filter['user.username'] . "%'";
                }
                unset($param1['user.username']);
            }

            if (isset($filter['user.nickname'])) {
                if (!empty($where_agent)) {
                    $where_agent = $where_agent . " and user.nickname like '%" . $filter['user.nickname'] . "%'";
                } else {
                    $where_agent = "user.nickname like '%" . $filter['user.nickname'] . "%'";
                }
                unset($param1['user.nickname']);
            }
            foreach ($param1 as $k => $v) {
                $where[$k] = $v;
            }
            list($where1, $sort, $order, $offset, $limit) = $this->buildparams();

            //var_dump($where);die;
            $list = $this->model
                ->alias('share_user')
                ->with('user')
                //->join('user u', 'u.id = share_user.user_id', 'LEFT')
                ->join('share_user_flags f', 'f.user_id = share_user.user_id', 'LEFT')
                ->where($where)
                ->where($where_agent)
                ->field('share_user.*,share_user.user_flags as u_user_flags,f.user_flags')
                ->order($sort, $order)
                //->fetchSql()->select();
                ->paginate($limit);
            //var_dump($list);die;
            foreach ($list as $key => &$row) {
                $mobile_xing = substr_replace($row["user"]["mobile"], '****', 3, 4);
                $username_xing = substr_replace($row["user"]["username"], '****', 3, 4);

                $row->visible(['id', 'user_flags', 'user_id', 'role', 'role_url', 'role1', 'role2', 'role3', 'role_type', 'addtime', 'parent_id', 'inviter_id', 'price', 'total_price', 'user.username', 'user.nickname', 'user.mobile', 'user.mobile_xing', 'user.username_xing', 'user.invitecode', 'score', 'amount']);

                $row["user"]["mobile_xing"] = $mobile_xing;
                $row["user"]["username_xing"] = $username_xing;
                //var_dump($row->toArray());die;
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        //数据统计开始

        $s = '%/' . 1;
        $sh_user = (new ShareUser())->where('role_url', 'like', $s)->where("role",'<>',0)->where(['is_delete' => 0])->select();
        $user_id_arr = array_column($sh_user, 'user_id');

        $where = ['share_user.user_id', 'in', $user_id_arr];
        $all_nums = $this->model->with('user')->where($where)->count();//总人数
        $all_score = $this->model->with('user')->where($where)->sum("share_user.score");//总积分
        $all_price = $this->model->with('user')->where($where)->sum("share_user.price");//总余额
        $all_lp_price = $this->model->with('user')->where($where)->sum("share_user.lp_price");//零批
        $all_old_price = $this->model->with('user')->where($where)->sum("share_user.old_price");//老余额
        $all_jin = $this->model->with('user')->where($where)->where("share_user.role", 6)->count();//金牌人数
        $all_yin = $this->model->with('user')->where($where)->where("share_user.role", 5)->count();//银牌人数
        $all_xing1 = $this->model->with('user')->where($where)->where("share_user.role", 3)->count();//一星网点
        $all_xing2 = $this->model->with('user')->where($where)->where("share_user.role", 4)->count();//二星网点
        $all_daiyan = $this->model->with('user')->where($where)->where("share_user.role", 2)->count();//代言人
        $all_tuiguang = $this->model->with('user')->where($where)->where("share_user.role", 1)->count();//推广员
        $data_["all_nums"] = $all_nums;//总人数
        $data_["all_score"] = $all_score;//总积分
        $data_["all_price"] = $all_price;//总余额
        $data_["all_lp_price"] = $all_lp_price;//
        $data_["all_old_price"] = $all_old_price;//
        $data_["all_jin"] = $all_jin;//金牌人数
        $data_["all_yin"] = $all_yin;//银牌人数
        $data_["all_xing1"] = $all_xing1;//一星网点
        $data_["all_xing2"] = $all_xing2;//二星网点
        $data_["all_daiyan"] = $all_daiyan;//代言人
        $data_["all_tuiguang"] = $all_tuiguang;//推广员
        $this->view->assign("data_", $data_);
        //数据统计结束
        return $this->view->fetch();
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $filter = json_decode($this->request->get('filter'), true);
            $param1 = json_decode($this->request->param('filter'), 1);
            $where_agent = 'share_user.id>0';
            $where = [];
            if (isset($filter['addtime'])) {
                $array = explode('-', $filter['addtime']);
                $begin = strtotime($array[0] . '-' . $array[1] . '-' . $array[2]);
                $end = strtotime($array[3] . '-' . $array[4] . '-' . $array[5]);
                if (!empty($where_agent)) {
                    $where_agent = $where_agent . " and share_user.addtime between " . $begin . ' and ' . "$end";
                } else {
                    $where_agent = "share_user.addtime between " . $begin . ' and ' . "$end";
                }
                unset($param1['addtime']);
            }
            //var_dump($param1);die;
            if (isset($param1['user_flags'])) {
                $where['f.user_flags'] = $param1['user_flags'];
                $param1['f.user_flags'] = $param1['user_flags'];
                unset($param1['user_flags']);
            }
            if (isset($param1['user_id'])) {
                $where['user.id'] = $param1['user_id'];
                $param1['user.id'] = $param1['user_id'];
                unset($param1['user_id']);
            }
            if (isset($filter['role_url'])) {
                if (!empty($where_agent)) {
                    $where_agent = $where_agent . " and role_url like '%" . $filter['role_url'] . "%'";
                } else {
                    $where_agent = "role_url like '%" . $filter['role_url'] . "%'";
                }
                unset($param1['role_url']);
            }

            if (isset($filter['user.staff'])) {
                if (!empty($where_agent)) {
                    $where_agent = $where_agent . " and user.staff =2";
                } else {
                    $where_agent = "user.staff =2";
                }
                unset($param1['role_url']);
            }
            if (isset($filter['user.mobile'])) {
                if (!empty($where_agent)) {
                    $where_agent = $where_agent . " and user.mobile like '%" . $filter['user.mobile'] . "%'";
                } else {
                    $where_agent = "user.mobile like '%" . $filter['user.mobile'] . "%'";
                }
                unset($param1['user.mobile']);
            }
            if (isset($filter['user.username'])) {
                if (!empty($where_agent)) {
                    $where_agent = $where_agent . " and user.username like '%" . $filter['user.username'] . "%'";
                } else {
                    $where_agent = "user.username like '%" . $filter['user.username'] . "%'";
                }
                unset($param1['user.username']);
            }
            if (isset($filter['user.nickname'])) {
                if (!empty($where_agent)) {
                    $where_agent = $where_agent . " and user.nickname like '%" . $filter['user.nickname'] . "%'";
                } else {
                    $where_agent = "user.nickname like '%" . $filter['user.nickname'] . "%'";
                }
                unset($param1['user.nickname']);
            }
            if (isset($filter['price'])) {
                $arr = explode(',',$filter['price']);
                if($arr[0] && $arr[1]){
                    $where_agent = $where_agent . " and  share_user.price > " . $arr[0] . " and share_user.price <".$arr[1];
                }elseif ($arr[0]){
                    $where_agent = $where_agent . " and  share_user.price > " . $arr[0];
                }elseif ($arr[1]){
                    $where_agent = $where_agent . " and share_user.price < " . $arr[1];
                }
                unset($param1['price']);
            }
            if (isset($filter['lp_price'])) {
                $arr = explode(',',$filter['lp_price']);
                if($arr[0] && $arr[1]){
                    $where_agent = $where_agent . " and  share_user.lp_price > " . $arr[0] . " and share_user.lp_price <".$arr[1];
                }elseif ($arr[0]){
                    $where_agent = $where_agent . " and  share_user.lp_price > " . $arr[0];
                }elseif ($arr[1]){
                    $where_agent = $where_agent . " and share_user.lp_price < " . $arr[1];
                }
                unset($param1['lp_price']);
            }
            if (isset($filter['old_price'])) {
                $arr = explode(',',$filter['old_price']);
                if($arr[0] && $arr[1]){
                    $where_agent = $where_agent . " and  share_user.old_price > " . $arr[0] . " and share_user.old_price <".$arr[1];
                }elseif ($arr[0]){
                    $where_agent = $where_agent . " and  share_user.old_price > " . $arr[0];
                }elseif ($arr[1]){
                    $where_agent = $where_agent . " and share_user.old_price < " . $arr[1];
                }
                unset($param1['old_price']);
            }
            if (isset($filter['advert_price'])) {
                $arr = explode(',',$filter['advert_price']);
                if($arr[0] && $arr[1]){
                    $where_agent = $where_agent . " and  share_user.advert_price > " . $arr[0] . " and share_user.advert_price <".$arr[1];
                }elseif ($arr[0]){
                    $where_agent = $where_agent . " and  share_user.advert_price > " . $arr[0];
                }elseif ($arr[1]){
                    $where_agent = $where_agent . " and share_user.advert_price < " . $arr[1];
                }
                unset($param1['advert_price']);
            }
            if (isset($filter['score'])) {
                $arr = explode(',',$filter['score']);
                if($arr[0] && $arr[1]){
                    $where_agent = $where_agent . " and  share_user.score > " . $arr[0] . " and share_user.score <".$arr[1];
                }elseif ($arr[0]){
                    $where_agent = $where_agent . " and  share_user.score > " . $arr[0];
                }elseif ($arr[1]){
                    $where_agent = $where_agent . " and share_user.score < " . $arr[1];
                }
                unset($param1['score']);
            }
            //echo $where_agent;exit;
            foreach ($param1 as $k => $v) {
                $where[$k] = $v;
            }
            list($where1, $sort, $order, $offset, $limit) = $this->buildparams();

            //var_dump($where);die;
            $list = $this->model
                ->alias('share_user')
                ->with('user')
                ->join('share_user_flags f', 'f.user_id = share_user.user_id', 'LEFT')
                ->where($where)
                ->where($where_agent)
                ->field('share_user.*,share_user.user_flags as u_user_flags,f.user_flags')
                ->order($sort, $order)
                //->fetchSql()->select();
                ->paginate($limit);
           // echo  $this->model->getlastsql();
            //var_dump($list);die;

            foreach ($list as $key => &$row) {
                if (preg_match("/^1[34578]{1}\d{9}$/", $row["user"]["mobile"])) {
                    $mobile_xing = substr_replace($row["user"]["mobile"], '****', 3, 4);
                } else {
                    $mobile_xing = $row["user"]["mobile"];
                }
                if (preg_match("/^1[34578]{1}\d{9}$/", $row["user"]["username"])) {
                    $username_xing = substr_replace($row["user"]["username"], '****', 3, 4);
                } else {
                    $username_xing = $row["user"]["username"];
                }

                $row->visible(['mutual_money','lp_price','id', 'user_flags', 'user_id', 'role', 'role_url', 'role1', 'role2', 'role3', 'role_type', 'addtime', 'parent_id', 'inviter_id', 'price', 'old_price', 'is_leader', 'advert_price', 'total_price', 'user.username', 'user.nickname', 'user.mobile', 'user.mobile_xing', 'user.username_xing', 'user.invitecode', 'score', 'amount']);

                $row["user"]["mobile_xing"] = $mobile_xing;
                $row["user"]["username_xing"] = $username_xing;

                //var_dump($row->toArray());die;
            }
            $list_tj = $this->model
                ->alias('share_user')
                ->with('user')
                ->join('share_user_flags f', 'f.user_id = share_user.user_id', 'LEFT')
                ->where($where)
                ->where($where_agent)
                ->field('sum(share_user.score) as all_score,sum(share_user.price) as all_price,sum(share_user.old_price) as all_old_price,sum(share_user.lp_price) as all_lp_price,sum(share_user.mutual_money) as all_mutual_money,sum(share_user.advert_price) as all_advert_price')
                ->find();
            $all_cou = $this->model
                ->alias('share_user')
                ->with('user')
                ->join('share_user_flags f', 'f.user_id = share_user.user_id', 'LEFT')
                ->where($where)
                ->where($where_agent)
                ->field("count(*) as cou,role")
                ->group("role")
                ->select();
            //echo $this->model->getlastsql();
            $all_tuiguang = 0;
            $all_daiyan = 0;
            $all_xing2 = 0;
            $all_xing1 = 0;
            $all_yin = 0;
            $all_jin = 0;
            foreach ($all_cou as $k=>$v){
                if($v['role'] == 1) {
                    $all_tuiguang =  $v['cou'];
                }
                if($v['role'] == 2) {
                    $all_daiyan =  $v['cou'];
                }
                if($v['role'] == 3) {
                    $all_xing1 =  $v['cou'];
                }
                if($v['role'] == 4) {
                    $all_xing2 =  $v['cou'];
                }
                if($v['role'] == 5) {
                    $all_yin =  $v['cou'];
                }
                if($v['role'] == 6) {
                    $all_jin =  $v['cou'];
                }
            }
            $s = '%/' . 1;
            $sh_user = (new ShareUser())->where('role_url', 'like', $s)->where("role",'<>',0)->where(['is_delete' => 0])->select();
            $all_nums = count($sh_user)+1;//总人数
            $result = array("total" => $list->total(), "rows" => $list->items(),
                'all_nums'=>$all_nums,
                'all_score'=>round($list_tj['all_score'],2),
                'all_price'=>round($list_tj['all_price'],2),
                'all_old_price'=>round($list_tj['all_old_price'],2),
                'all_lp_price'=>round($list_tj['all_lp_price'],2),
                'all_advert_price'=>round($list_tj['all_advert_price'],2),
                'all_mutual_money'=>round($list_tj['all_mutual_money'],2),
                'all_jin'=>$all_jin,
                'all_yin'=>$all_yin,
                'all_xing1'=>$all_xing1,
                'all_xing2'=>$all_xing2,
                'all_daiyan'=>$all_daiyan,
                'all_tuiguang'=>$all_tuiguang,
            );

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $users = FUser::get($row['user_id']);
        $row['mobile'] = $users['mobile'];
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;

        //独立分割
       /* $share_user = \db("share_user")->where('user_id', $row['user_id'])->find();
        if ($params['is_sep_income'] == 1 && $share_user['is_sep_income'] == 0) {
            $arr = (new ShareUser())->setSepTeamUser($users['id']);
            if (is_array($arr) && $arr['code'] == 0) {
                $this->error($arr['msg']);
            }

            $this->success();
        }*/

        Db::startTrans();
        try {
            if ($params['mobile'] != $users['mobile'] && FUser::getByMobile($params['mobile'])) {
                exception('手机号已存在');
                return false;
            }

            if ($params['mobile'] != $users['mobile']) {
                if (!Validate::regex($params['mobile'], "^1\d{10}$")) {
                    exception('手机号填写错误');
                }
                $before_mobile = $params['mobile'];
                $users->username = $params['mobile'];
                $users->mobile = $params['mobile'];
                $users->save();
                UserChangeLog::create(['user_id' => $users->id, 'before_mobile' => $before_mobile, 'after_mobile' => $params['mobile'], 'memo' => '后台操作变更手机号']);
            }

            if ((int)$params['role'] < (int)$row['role']) {
                $this->error(__('级别不能降低'));
                exception('级别不能降低');
                return false;
            }

            if ((int)$params['role'] > (int)$row['role']) {
                $ShareConfig = ShareConfig::where(['role' => $params['role'], 'type' => 2])->find();
                $amount = empty($ShareConfig) ? $row['amount'] : $ShareConfig['reward'];
                $amount = ($row['amount'] > $amount) ? $row['amount'] : $amount;
                $params['amount'] = $amount;
                $params['manual_role'] = 1;
                //变更级别记录日志
                ShareUserRoleLog::create(['user_id' => $row['user_id'], 'before_role' => $row['role'], 'after_role' => $params['role'], 'before_amount' => $row['amount'], 'after_amount' => $amount, 'memo' => '后台操作变更级别']);
            } elseif ((int)$params['role'] < (int)$row['role']) {
                $ShareConfig = ShareConfig::where(['role' => $params['role'], 'type' => 2])->find();
                $amount = empty($ShareConfig) ? $row['amount'] : $ShareConfig['reward'];
                $amount = ($row['amount'] < $amount) ? $row['amount'] : $amount;
                $params['amount'] = $amount;
                $params['manual_role'] = 1;
                //变更级别记录日志
                ShareUserRoleLog::create(['user_id' => $row['user_id'], 'before_role' => $row['role'], 'after_role' => $params['role'], 'before_amount' => $row['amount'], 'after_amount' => $amount, 'memo' => '后台操作变更级别']);
            }

            $result = $row->allowField(true)->save($params);

            // 升级分销商
            $this->model->promotion_save($row['parent_id'], $params['role'], $row['role_type']);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
//            $this->error($e->getMessage());
        }

        if (false === $result) {
            $this->error(__('No rows were updated'));
        }

        $this->success();
    }

    public function change($ids = null)
    {
        if ($this->request->isAjax()) {
            $row = $this->model->get($ids);
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            $user_id = $row['user_id'];

            $params = $this->request->post('row/a');
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $mobile = $params['mobile'];
            $model = new Change();
            $pa_count = Db::name("share_user")->where(['parent_id' => $user_id])->count();
            if ($pa_count >= 3) {
                $this->error(__('手动设置用户下级已满'));
            }

            $user = DB::name('user')->where('mobile', $mobile)->find();
            if (!$user) {
                $this->error("手机号不存在");
            }

            $cur_user = \db('share_user')->where('user_id', $user_id)->find();


            $bg_user_data = Db::name("share_user")->where('user_id', $user['id'])->find();
            $old_id = Db::name("share_user")->where('user_id', $user['id'])->value('parent_id');

            $s = '%/' . $user['id'] . '/%';
            $sonShareAll = (new ShareUser())->where('role_url', 'like', $s)->whereOr(['user_id'=>$user['id']])
                ->order("role desc")
                ->find();
            $old_id_type_role = $sonShareAll['role'];

            $new_id = $user_id;
            $user_id = $user['id'];
            $new_info = Db::name("share_user")->where(['user_id' => $new_id])->find();

            if ($new_id == $old_id) {
                $this->error("当前节点不需要改变");
            }
            if ($new_id == $user_id) {
                $this->error("不可以自己做自己节点");
            }

            if (in_array($user['id'], explode('/', $cur_user['role_url']))) {
                $this->error("上级节点不能切进来");
            }


            $Share = new ShareUser();
            $list = Db::name("share_user")->where(['parent_id' => $new_id])->select();
            foreach ($list as $k => $v) {
                Db::name("share_user")->where('user_id', $v['user_id'])->update(['role_type' => $k+1]);
            }
            $temp_data['pid'] = $new_id;
            $temp_data['parent_user_id'] = $new_id;
            $temp_data['role_type'] = count($list) + 1;
            $role_type = $temp_data['role_type'];
            // role_url
            $role = $new_info['role'];
            //查询是否为分割用户
            $is_fla = 0;
            $fla_data = Db::name("share_user_flags")->where(['user_id'=>$row['user_id']])->find();
            if($fla_data){
                $is_fla = 1;
            }

            Db::name("share_user")->where('user_id', $user_id)->update(['parent_id' => $new_id, 'inviter_id' => $new_id, 'role_type' => $role_type]);
            DB::name('user')->where('mobile', $mobile)->update($temp_data);

            $all_node = $this->get_team($user_id);

            $list = Db::name("share_user")->where('user_id', 'in', implode(',', $all_node))->select();
            $old_url = Db::name("share_user")->where('user_id', $user_id)->value('role_url');
            $new_url = Db::name("share_user")->where('user_id', $new_id)->value('role_url');
            $new_url = '/' . $new_id . $new_url;
            $fzArr = [];
            if($is_fla == 1){
                Db::name("share_user_flags")->where(['user_id'=>$row['user_id']])->delete();
                $ins['user_id'] = $row['user_id'];
                $ins['user_flags'] = $fla_data['user_flags'];
                $ins['addtime'] = time();
                $fzArr[] = $ins;
            }
           // $new_share_data = Db::name("share_user")->where(['user_id'=>$new_id])->find();
           // $tye_h_role = $new_share_data['role'];
            foreach ($list as $v) {
               /* if($v['role'] >$tye_h_role){
                    $tye_h_role = $v['role'];
                }*/
                $v['role_url'] = str_replace($old_url, $new_url, $v['role_url']);
                Db::name("share_user")->where('user_id', $v['user_id'])->update(['role_url' => $v['role_url']]);
                Db::name("share_user_flags")->where(['user_id'=>$v['user_id']])->delete();
                if($is_fla == 1){
                    $ins['user_id'] = $v['user_id'];
                    $ins['user_flags'] = $fla_data['user_flags'];
                    $ins['addtime'] = time();
                    $fzArr[] = $ins;
                }
            }

           // Db::name("share_user")->where(['user_id'=>$new_id])->update(["role".$role_type => $tye_h_role]);
            if(count($fzArr) > 0){
                db('share_user_flags')->insertAll($fzArr);
            }
            //老节点团队信息更改
            //更新团队123 级别 和团队人数

            (new CommonShare())->chageTeamSum($bg_user_data['parent_id'],$bg_user_data['role_type'],$bg_user_data['user_id'],1);

            //更新团队123 级别
            model('\app\admin\model\share\ShareUser')->setTeamUser($old_id, $new_id);

            //(new ShareUser())->promotion_save($new_id, $role, $role_type);
            file_put_contents('ts.txt',$new_id.", ".$old_id_type_role.",". $role_type);
            (new ShareUser())->promotion_save($new_id, $old_id_type_role, $role_type);
            $old_role_url = $row['role_url'];
            $model->save(compact('user_id', 'old_id', 'new_id', 'old_role_url'));
            $this->success("操作成功");
        }
        return $this->view->fetch();
    }

    /**
     * @param $user_id
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * 获取团队信息
     */
    protected function get_team($user_id)
    {
        $users = \db("share_user")->where('role_url', 'like', '%/' . $user_id . '/%')
            ->field('user_id')->select();
        return array_merge([$user_id], array_column($users, 'user_id'));
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $row = $this->model->get($ids);

        $this->userinfo_del($row['id']);
        $this->success();
    }

    public function userinfo_del($pid)
    {
        //齐10。31
        $share_user = Db::name('share_user')->where(['id' => $pid])->find();
        if ($share_user['user_id'] < 10000) {
            $this->error(__("该用户不能删除"));
        }
        $sum = (new ShareUser())->re_user_sum($share_user['user_id'], 1);
        if ($sum >= 4) {
            $this->error(__("下级超过3，不允许删除"));
        }
        if (!empty($share_user)) {
            $share_user['shareuserid'] = $share_user['id'];
            unset($share_user['id']);
            $share_user_insert = Db::name("share_user_delete")->strict(false)->insert($share_user);
            if (!$share_user_insert) {
                $this->error(__("添加失败"));
            }
            $share_user_delete = Db::name('share_user')->where(['id' => $share_user['shareuserid']])->delete();
            Db::name('share_user_flags')->where(['user_id' => $share_user['shareuserid']])->delete();
            if (!$share_user_delete) {
                $this->error(__("删除失败"));
            }
        }

        $user = Db::name('user')->where(['id' => $share_user['user_id']])->find();
        if (!empty($user)) {
            $user['uid'] = $user['id'];
            unset($user['id']);
            $user_insert = Db::name("user_delete")->strict(false)->insert($user);
            if (!$user_insert) {
                $this->error(__("添加失败"));
            }
            Auth::instance()->delete($user['uid']);
//            $user_delete = Db::name('user')->where(['id' => $user['uid']])->delete();
//            if (!$user_delete) {
//                $this->error(__("删除失败"));
//            }
        }

        $where['parent_id'] = ['in', $share_user['user_id']];
        $share_users = Db::name('share_user')->where($where)->select();
        if ($share_users) {
            foreach ($share_users as $item) {
                $this->userinfo_del($item['id']);
            }
        }
        //删除好友关系
        (new CommonShare())->delUserf($share_user['user_id']);
        return true;
    }


    /**
     * 详情
     */
    public function detail($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $user = FUser::get($row['user_id']);

        $share_user = Db::name("share_user")->where(['user_id' => $row['user_id']])->find();
        $parent_user = Db::name("share_user")->where(['user_id' => $row['parent_id']])->find();
        $flags = Db::name("share_user_flags")->where(['user_id' => $row['user_id']])->find();

        $user_parent = FUser::get($row['parent_id']);
        $row->nickname = empty($user) ? '无' : $user['nickname'];
        $row->mobile = empty($user) ? '无' : $user['mobile'];
        $row->parent_mobile = empty($user_parent) ? '无' : $user_parent['mobile'];
        $row->parent_nickname = empty($user_parent) ? '无' : $user_parent['nickname'];
        $row->parent_role = empty($parent_user) ? '无' : $parent_user['role'];
        $row->is_sep_income = empty($share_user) ? '无' : $share_user['is_sep_income'];
        $row->user_flags = empty($flags) ? '无' : $flags['user_flags'];
        $this->view->assign("row", $row->toArray());

        //数据统计开始
        $user_id = $row['user_id'];
        $all_nums = $this->model
            ->where(['role_url' => ['like', "%" . '/' . $row['user_id'] . $row['role_url'] . "%"]])
            ->whereOr("user_id", $row['user_id'])
            ->count();//总人数
        //->fetchSql()->select();
        //var_dump($all_nums);die;
        $all_score = $this->model->with('user')
            ->where(['role_url' => ['like', "%" . '/' . $row['user_id'] . $row['role_url'] . "%"]])
            ->whereOr("user_id", $row['user_id'])
            ->sum("share_user.score");//总积分
        $all_price = $this->model->with('user')->where(['role_url' => ['like', "%" . '/' . $row['user_id'] . $row['role_url'] . "%"]])->whereOr("user_id", $row['user_id'])->sum("share_user.price");//总余额
        $all_lp_price = $this->model->with('user')->where(['role_url' => ['like', "%" . '/' . $row['user_id'] . $row['role_url'] . "%"]])->whereOr("user_id", $row['user_id'])->sum("share_user.lp_price");//
        $all_old_price = $this->model->with('user')->where(['role_url' => ['like', "%" . '/' . $row['user_id'] . $row['role_url'] . "%"]])->whereOr("user_id", $row['user_id'])->sum("share_user.old_price");//
        $all_jin = $this->model->with('user')
            ->where(['role_url' => ['like', "%" . '/' . $row['user_id'] . $row['role_url'] . "%"]])
            ->where("share_user.role", 6)
            ->where(function ($query) use ($user_id, $row) {
                $query->whereOr(['role_url' => ['like', "%" . '/' . $user_id . $row['role_url'] . "%"]])
                    ->whereOr("user_id", $user_id);
            })
            ->count();//金牌人数
        $all_yin = $this->model->with('user')
            ->where("share_user.role", 5)
            ->where(function ($query) use ($user_id, $row) {
                $query->whereOr(['role_url' => ['like', "%" . '/' . $user_id . $row['role_url'] . "%"]])
                    ->whereOr("user_id", $user_id);
            })
            ->count();//银牌人数
        $all_xing1 = $this->model->with('user')
            ->where(function ($query) use ($user_id, $row) {
                $query->whereOr(['role_url' => ['like', "%" . '/' . $user_id . $row['role_url'] . "%"]])
                    ->whereOr("user_id", $user_id);
            })
            ->where("share_user.role", 3)
            ->count();//一星网点
        $all_xing2 = $this->model->with('user')
            ->where(function ($query) use ($user_id, $row) {
                $query->whereOr(['role_url' => ['like', "%" . '/' . $user_id . $row['role_url'] . "%"]])
                    ->whereOr("user_id", $user_id);
            })
            ->where("share_user.role", 4)
            ->count();//二星网点
        $all_daiyan = $this->model->with('user')
            ->where(function ($query) use ($user_id, $row) {
                $query->whereOr(['role_url' => ['like', "%" . '/' . $user_id . $row['role_url'] . "%"]])
                    ->whereOr("user_id", $user_id);
            })
            ->where("share_user.role", 2)
            ->count();//代言人
        $all_tuiguang = $this->model->with('user')
            ->where(function ($query) use ($user_id, $row) {
                $query->whereOr(['role_url' => ['like', "%" . '/' . $user_id . $row['role_url'] . "%"]])
                    ->whereOr("user_id", $user_id);
            })
            ->where("share_user.role", 1)
            ->count();//推广员
        $data_["all_nums"] = $all_nums;//总人数
        $data_["all_score"] = $all_score;//总积分
        $data_["all_price"] = $all_price;//总余额
        $data_["all_lp_price"] = $all_lp_price;//总余额
        $data_["all_old_price"] = $all_old_price;//总余额
        $data_["all_jin"] = $all_jin;//金牌人数
        $data_["all_yin"] = $all_yin;//银牌人数
        $data_["all_xing1"] = $all_xing1;//一星网点
        $data_["all_xing2"] = $all_xing2;//二星网点
        $data_["all_daiyan"] = $all_daiyan;//代言人
        $data_["all_tuiguang"] = $all_tuiguang;//推广员
        $this->view->assign("data_", $data_);
        //数据统计结束

        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public
    function pwd($ids)
    {
        $pwd = $this->getEncryptPassword("123456", 123456);
        exit;
        $save_status = Db::name("user")->where(['user_id' => $ids])->update(['password' => $pwd, 'salt' => 123456]);
        if ($save_status) {
            $this->error(__("密码重置成功"));
        } else {
            $this->error(__("密码重置失败"));
        }
    }

    public
    function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

    public
    function resetpwd($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $user = FUser::get($row['user_id']);
        $salt = \fast\Random::alnum();
        $user->password = \app\common\library\Auth::instance()->getEncryptPassword('123456', $salt);
        $user->salt = $salt;
        $res = $user->save();
        $pa_data = Db::name("pay_passwd")->where(['user_id'=>$row['user_id']])->find();
        $in_data['user_id'] = $row['user_id'];
        $in_data['type'] = "md5";
        $in_data['err_num'] = 0;
        $in_data['passwd'] = md5(substr($user['mobile'],-4));
        if($pa_data){
            $in_status = Db::name("pay_passwd")->where(['user_id'=>$row['user_id']])->update($in_data);
        }else{
            $in_status = Db::name("pay_passwd")->insert($in_data);
        }
        if ($res && $in_status !== false) {
            $this->error(__("密码重置成功"));
        } else {
            $this->error(__("密码重置失败"));
        }
    }

    public function addchange($ids = null)
    {
        $params = $this->request->post('row/a');
        if ($params['mobile']) {
            $row = $this->model->get($ids);
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            $user_id = $row['user_id'];

            $params = $this->request->post('row/a');
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $mobile = $params['mobile'];
            $nickname = $params['nickname'];

            //判断节点是否已满 sxc 10-29
            $Share = new ShareUser();
            $get_parent = $Share->get_parent_id_two($user_id);//原方法 判断节点是否满员
            $get_parent_id = empty($get_parent) ? 0 : $get_parent[0];
            $role_type = empty($get_parent) ? 0 : $get_parent[1];
            if ($get_parent_id == 0) {
                $this->error("邀请码已满额");
            }

            $id = DB::name('user')->where('mobile', $mobile)->value('id');
            if ($id) {
                $this->error("手机号已存在");
            }
            $uin_add['nickname'] = $nickname;
            $uin_add['mobile'] = $mobile;
            $uin_add['username'] = $mobile;
            $uin_add['pid'] = $user_id;
            $uin_add['password'] = '5f1d7a84db00d2fce00b31a7fc73224f';
            $uin_add['salt'] = '123456';
            $uin_add['status'] = 'normal';

            //此处需要给出所在部门
            $temp_data['invitecode'] = $mobile;
            $temp_data['pid'] = $get_parent_id;
            $temp_data['parent_user_id'] = $user_id;

            $temp_data['role_type'] = $role_type + 1;
            $temp_data['score'] = 0.01;
            $temp_data['nickname'] = $nickname;

            $ret = (new Auth())->register($mobile, "123456", '', $mobile, $temp_data);
            if ($ret) {
                $this->success("操作成功");
            } else {
                $this->error("添加失败");
            }
        }
        return $this->view->fetch();
    }

    private function getSepTeamUser($userId)
    {
        //$user =(new ShareUser())->get(['user_id'=>$this->user_id]); // 分销用户
        //$puser =(new ShareUser())->get(['user_id'=>$user->parent_id]);

        $teamlist = Db::table('share_user')->where(['is_sep_income' => 1])->select();
        $teamUidArr = [];
        $noteamUidArr = [];
        if (!empty($teamlist)) {
            foreach ($teamlist as $val) {
                $puserlist = Db::table('share_user')->where(['role_url' => ['like', "%" . $val['user_id'] . "%"]])->order('id DESC')->select();
                $userIdsStr = '';
                foreach ($puserlist as $vv) {
                    $userIdsStr = $userIdsStr . $val['role_url'] . '/' . $vv['user_id'];
                }

//                foreach($puserlist as $vl) {
                $userArray = explode('/', $userIdsStr);
                $teamArray = array_filter($userArray);
                $teamArray = array_merge($teamArray, [$val['user_id']]);
                //$isSepIncome = Db::table('share_user')->where(['user_id'=>['IN', $teamArray], 'is_sep_income'=>1])->count();
                if (in_array($userId, $teamArray)) {
                    foreach ($teamArray as $k => $uid) {
                        if ($uid >= $val['user_id']) {
                            $teamUidArr[$k] = $uid;
                        } else {
                            $noteamUidArr[$k] = $uid;
                        }
                    }
                    break;
                }
//                }
            }
        }
        $teamUidArr = array_unique($teamUidArr);
        $noteamUidArr = array_unique($noteamUidArr);
        return ['team_user' => $teamUidArr, 'noteam_user' => $noteamUidArr];
    }

    public function userdel($ids = null)
    {

        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $da = Db::name("user_id_card")->where(['user_id' => $row['user_id']])->find();
        if (!$da) {
            $this->error("此用户没有实名，不用删除");
        }
        $res = Db::name("user_id_card")->where(['user_id' => $row['user_id']])->delete();
        if ($res) {
            $this->error(__("删除成功"));
        } else {
            $this->error(__("删除失败"));
        }
    }

    /**
     * 禁用
     */
    public function disable($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Db::startTrans();
        $share_status = Db::name("share_user")->where(['id' => $ids])->update(['role' => 0]);
        $u_status = Db::name("user")->where(['id' => $row['user_id']])->update(['status' => 'forbidden']);
        if ($share_status !== false && $u_status) {
            Db::commit();
            $this->success("禁用成功");
        } else {
            Db::rollback();
            $this->error(__($share_status . "禁用失败" . $u_status));
        }

    }

    /**
     * 取消分割
     */
    public function unincome($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $user = \db("share_user")->where('user_id', $row['user_id'])->find();

        if (empty($user['user_flags'])) {
            $this->error('不是节点人，不能取消分割');
        }

        $sh_user = Db::name("share_user")->where('role_url', 'like', '%/' . $row['user_id'] . '/%')->select();
        $user_id_arr = array_column($sh_user, 'user_id');
        $user_id_arr = array_merge($user_id_arr, [$row['user_id']]);
        Db::name("share_user")->where('user_id', $row['user_id'])->update(['is_sep_income' => 0, 'user_flags' => '']);
        Db::name("share_user_flags")->where('user_id', 'in', $user_id_arr)->delete();
        $this->success("取消分割成功");
    }
    public function setSepTeam($ids = null){
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $share_user = \db("share_user")->where('user_id', $row['user_id'])->find();
        if ($share_user['is_sep_income'] == 0) {
            $arr = (new ShareUser())->setSepTeamUser($row['user_id']);
            if (is_array($arr) && $arr['code'] == 0) {
                $this->error($arr['msg']);
            }

            $this->success("设置成功");
        }else{
            $this->error('已经是独立分割');
        }
    }

    /**
     * @param $ids
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     *独立负责人的资金转给独立负责人
     */
    public function sepIncomeMoney($ids = null){
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $share_user = \db("share_user s")
            ->field("u.mobile,s.is_sep_income,s.user_flags,s.user_id")
            ->join("user u","u.id=s.user_id", 'LEFT')
            ->where('s.user_id', $row['user_id'])->find();
        if ($share_user['is_sep_income'] == 1) {
            $flags_list = Db::name("share_user_flags f")
                ->field("u.mobile,f.user_id,s.old_price,s.score")
                ->join("user u","u.id=f.user_id", 'LEFT')
                ->join("share_user s","s.user_id=f.user_id", 'LEFT')
                ->where(['f.user_flags'=>$share_user['user_flags']])
                ->where('u.staff','<>',2)
                ->where("f.user_id","<>",$row['user_id'])->select();
            $db = Db::startTrans();
            foreach ($flags_list as $k=>$v){
                if($v['old_price'] > 0){ //
                    $re_data1 = (new ShareUser)->userPriceLog($v['user_id'], -$v['old_price'], 13, $memo = '全部中军值兑换股票权益（可联系负责人）',$db,['is_old'=>1,'mobile'=>$share_user['mobile']]);
                    $re_data2 = (new ShareUser)->userPriceLog($share_user['user_id'], $v['old_price'], 7, $memo = '金额转让',$db,['is_old'=>1,'mobile'=>$v['mobile']]);
                    if($re_data1['status'] == 0 || $re_data2['status'] == 0){
                        Db::rollback();
                        $this->error($re_data1['msg']."失败1".$re_data2['msg']);
                    }
                }
                if($v['score'] > 0){ //
                    $re_data3 = (new ShareUser)->userScoreLog($v['user_id'], -$v['score'], 9, $memo = '全部余额兑换股票权益（可联系负责人）',$db,['mobile'=>$share_user['mobile']]);
                    $re_data4 = (new ShareUser)->userScoreLog($share_user['user_id'], $v['score'], 6, $memo = '积分转让',$db,['mobile'=>$v['mobile']]);
                    if($re_data3['status'] == 0 || $re_data4['status'] == 0){
                        Db::rollback();
                        $this->error($re_data3['msg']."失败2".$re_data4['msg']);
                    }
                }

            }
            Db::commit();
            $this->success("成功");
        }else{
            $this->error('不是独立分割人');
        }
    }
}
